package com.hk.employeemanagementsystem.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hk.employeemanagementsystem.dto.AdvanceSearchEmpDto;
import com.hk.employeemanagementsystem.entity.EmployeeEntity;
import com.hk.employeemanagementsystem.service.EmployeeEntityService;
import com.hk.employeemanagementsystem.util.web.WebCode;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.CORBA.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by 何坤
 * @Classname EmployeeController
 * @Description TODO
 * @Date 2019/12/19 9:37
 */
@RestController
@RequestMapping(value = "/emp")
public class EmployeeController {
    private Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private EmployeeEntityService employeeEntityService;

    @GetMapping(value = "/get")
    public Map<String, Object> selectEmployee(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Map<String, Object> tips = new HashMap<>();
        try {
            PageHelper.startPage(pageNumber, pageSize);
            List<EmployeeEntity> employeeEntities = employeeEntityService.selectAllEmployee();
            PageInfo pageInfo = new PageInfo<EmployeeEntity>(employeeEntities);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", pageInfo);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }

    @GetMapping(value = "/get/{id}")
    public Map<String, Object> getEmployeeById(@PathVariable("id") Integer id){
        Map<String, Object> tips = new HashMap<>();
        try {
            EmployeeEntity employeeEntity = employeeEntityService.getEmployeeById(id);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", employeeEntity);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }

    @PostMapping(value = "/save")
    public Map<String, Object> saveEmployee(@RequestBody EmployeeEntity employeeEntity){
        Map<String, Object> tips = new HashMap<>();
        try {
            logger.info(employeeEntity.toString());
            Boolean exist = employeeEntityService.validatorWorkIdUniqueness(employeeEntity.getWorkId());
            logger.info(String.valueOf(exist)+"----------------");
            if (exist) {
                employeeEntityService.update(employeeEntity, new QueryWrapper<EmployeeEntity>().eq("emp_work_id", employeeEntity.getWorkId()));
            } else {
                employeeEntityService.saveEmployee(employeeEntity);
            }
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
        }
        return tips;
    }

    @GetMapping(value = "/validatorWorkId")
    public Map<String, Object> validatorWorkIdUniqueness(@RequestParam("workId") String workId){
        Map<String, Object> tips = new HashMap<>();
        try {
            Boolean exist = employeeEntityService.validatorWorkIdUniqueness(workId);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", exist);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    @GetMapping(value = "/validatorPhone")
    public Map<String, Object> validatorPhoneUniqueness(@RequestParam(name = "phone") String phone,
                                                        @RequestParam(value = "workId", required = false) String workId){
        Map<String, Object> tips = new HashMap<>();
        try {
            Boolean exist = employeeEntityService.validatorPhoneUniqueness(phone, workId);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", exist);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }


    @GetMapping(value = "/validatorEmail")
    public Map<String, Object> validatorEmailUniqueness(@RequestParam(name = "email") String email,
                                                        @RequestParam(name = "workId", required = false) String workId){
        Map<String, Object> tips = new HashMap<>();
        try {
            Boolean exist = employeeEntityService.validatorEmailUniqueness(email, workId);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", exist);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    @GetMapping(value = "/validatorIdCard")
    public Map<String, Object> validatorIdCardUniqueness(@RequestParam(name = "idCard") String idCard,
                                                         @RequestParam(name = "workId", required = false) String workId){
        Map<String, Object> tips = new HashMap<>();
        try {
            Boolean exist = employeeEntityService.validatorIdCardUniqueness(idCard, workId);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", exist);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    @DeleteMapping(value = "/delete")
    public Map<String, Object> deleteEmployee(@RequestBody List<Integer> deleteList){
        Map<String, Object> tips = new HashMap<>();
        try {
            boolean flag = employeeEntityService.removeByIds(deleteList);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", flag);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    /*@GetMapping(value = "/export")
    public void exportEmployee(OutputStream outputStream){
        try {
            List<EmployeeEntity> collection = employeeEntityService.selectAllEmployee();
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet();
            XSSFRow row = sheet.createRow(0);
            String[] cellNames = {"工号", "姓名", "性别", "手机", "邮箱", "身份证号码", "出生日期",
                    "所在地区", "详细地址", "籍贯", "婚姻状况", "民族", "政治面貌", "部门", "职位", "职称",
                    "等级", "聘用形式", "入职时间", "在职状态", "转正日期", "离职日期", "合同起始日期",
                    "合同结束日期", "合同时长", "工龄", "学历", "毕业院校", "专业"};
            for (int i=0; i<cellNames.length; i++){
                row.createCell(i).setCellValue(cellNames[i]);
            }
            for (int i=1; i<collection.size(); i++){
                XSSFRow row2 = sheet.createRow(i);
                for (EmployeeEntity employeeEntity : collection) {
                    row2.createCell(0).setCellValue(employeeEntity.getWorkId());
                    row2.createCell(1).setCellValue(employeeEntity.getName());
                    row2.createCell(2).setCellValue(employeeEntity.getGender());
                    row2.createCell(3).setCellValue(employeeEntity.getPhone());
                    row2.createCell(4).setCellValue(employeeEntity.getEmail());
                    row2.createCell(5).setCellValue(employeeEntity.getIdCard());
                    row2.createCell(6).setCellValue(employeeEntity.getBirthday());
                    row2.createCell(7).setCellValue(employeeEntity.getAddressRegion());
                    row2.createCell(8).setCellValue(employeeEntity.getAddressDetailed());
                    row2.createCell(9).setCellValue(employeeEntity.getNativePlace());
                    row2.createCell(10).setCellValue(employeeEntity.getMaritalStatus() ? "已婚" : "未婚");
                    row2.createCell(11).setCellValue(employeeEntity.getNation().getName());
                    row2.createCell(12).setCellValue(employeeEntity.getPolitical().getName());
                    row2.createCell(13).setCellValue(employeeEntity.getDepartment().getName());
                    row2.createCell(14).setCellValue(employeeEntity.getPosition().getName());
                    row2.createCell(15).setCellValue(employeeEntity.getJobLevel().getName());
                    row2.createCell(16).setCellValue(employeeEntity.getJobLevel().getTitleLevel());
                    row2.createCell(17).setCellValue(employeeEntity.getHireForm());
                    row2.createCell(18).setCellValue(employeeEntity.getBeginDate());
                    row2.createCell(19).setCellValue(employeeEntity.getWorkStatus() ? "在职" : "离职");
                    row2.createCell(20).setCellValue(employeeEntity.getConversionTime());
                    row2.createCell(21).setCellValue(employeeEntity.getTermDate());
                    row2.createCell(22).setCellValue(employeeEntity.getContractStartTime());
                    row2.createCell(23).setCellValue(employeeEntity.getContractEndTime());
                    row2.createCell(24).setCellValue(employeeEntity.getContractTerm());
                    row2.createCell(25).setCellValue(String.valueOf(employeeEntity.getWorkAge() == null ? 0 : employeeEntity.getWorkAge()));
                    row2.createCell(26).setCellValue(employeeEntity.getHighestEducation());
                    row2.createCell(27).setCellValue(employeeEntity.getSchool());
                    row2.createCell(28).setCellValue(employeeEntity.getSpecialty());
                }
            }
            wb.write(outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }
    }*/


    @GetMapping(value = "/basicSearch")
    public Map<String, Object> searchEmpByWorkId(@RequestParam(value = "workId") String workId,
                                                 @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                 @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Map<String, Object> tips = new HashMap<>();
        try {
            PageHelper.startPage(pageNumber, pageSize);
            List<EmployeeEntity> employeeEntities = employeeEntityService.selectEmployeeByWorkId(workId);
            PageInfo pageInfo = new PageInfo<EmployeeEntity>(employeeEntities);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", pageInfo);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    @PostMapping("/advanceSearch")
    public Map<String, Object> advancedSearch(@RequestBody AdvanceSearchEmpDto advanceSearchEmpDto){
        Map<String, Object> tips = new HashMap<>();
        logger.info(advanceSearchEmpDto.toString());
        try {
            PageHelper.startPage(advanceSearchEmpDto.getPageNumber(), advanceSearchEmpDto.getPageSize());
            List<EmployeeEntity> employeeEntities = employeeEntityService.advanceSearchEmp(advanceSearchEmpDto);
            PageInfo pageInfo = new PageInfo<EmployeeEntity>(employeeEntities);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", pageInfo);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }
}
